package com.cn.gxa.redisutils.intercept;

import com.cn.gxa.redisutils.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginIntercept  implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("========  CheckTokenIntercept  拦截器 ================ "+request.getRequestURL());
        //  响应的设置
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin")); // *允许任意地址访问，当前解决跨域后携带cookie问题
        response.setHeader("Access-Control-Allow-Credentials", "true"); //是否包含cookie，如果不包含，可省略
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PATCH,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization,Cookie,Accept,Token,Origin");
        //获得头部信息
        String  token =request.getHeader("token");
        //验证token 是否存在
        if(userService.checkToken(token)){
            return true;
        }
        //输出结果集
        response.sendRedirect("/toLogin");
        return   false;

    }


}
